package sddz.foodmanage.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SPUtils;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.base.BaseActivity;
import sddz.foodmanage.model.ResultBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.MyUtils;
import sddz.foodmanage.utils.SpfUtils;

/**
 * @Date:2019/7/2
 * @Author:lbb 修改登录密码
 */
public class ChangePasswordActivity extends BaseActivity {

    @BindView(R.id.title_navigation_icon)
    ImageView titleNavigationIcon;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.title_menu_icon)
    ImageView titleMenuIcon;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.image_title_right)
    ImageView imageTitleRight;
    @BindView(R.id.et_login_pwd)
    EditText etLoginPwd;
    @BindView(R.id.et_new_login_pwd)
    EditText etNewLoginPwd;
    @BindView(R.id.et_new_again_login_pwd)
    EditText etNewAgainLoginPwd;
    @BindView(R.id.bt_alter_login_pwd)
    Button btAlterLoginPwd;
    @BindView(R.id.activity_change_password)
    AutoLinearLayout activityChangePassword;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);
        ButterKnife.bind(this);
        initView();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initView() {
        titleText.setText("修改登录密码");
    }

    @OnClick({R.id.title_navigation_icon, R.id.bt_alter_login_pwd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_navigation_icon:
                finish();
                break;
            case R.id.bt_alter_login_pwd:
                submit();
                break;
        }
    }

    private void submit() {
        String oldPassword = etLoginPwd.getText().toString().trim();
        String newPassword = etNewLoginPwd.getText().toString().trim();
        String againPassword = etNewAgainLoginPwd.getText().toString().trim();

        if (TextUtils.isEmpty(oldPassword) || TextUtils.isEmpty(newPassword) || TextUtils.isEmpty(againPassword)) {
            show("密码不能为空");
            return;
        }

        if (oldPassword.length() < 6 || newPassword.length() < 6 || againPassword.length() < 6) {
            show("密码长度必须大于6个字符");
            return;
        }

        if (!newPassword.equals(againPassword)) {
            show("新密码和确认密码不相同");
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("_method", "put");
        params.put("password", newPassword);
        params.put("password_confirmation", againPassword);
        params.put("o_password", oldPassword);
        dialog.show();
        HttpUtils.getInstance().POST(mActivity, API.getupdatePassword, JSON.toJSONString(params), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                dialog.dismiss();
                Log.e("修改密码返回的数据", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                       int code= jsonObject.optInt("status_code");
                        if(!jsonObject.optString("message").equals("")) {
                            show(jsonObject.optString("message"));
                        }
                        if(code==200){
                            finish();
                        }else if(code==210){
                           String token=jsonObject.optJSONObject("data").optString("token");
                            Log.e("33333333", token);
                            SpfUtils.savetoken(mActivity,token);
                            submit();
                        }else if(code==401){
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                dialog.dismiss();
                Log.e("ssss", e.toString());
                show("访问数据失败，请稍后重试");
            }
        });
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("ChangePassword Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}
